﻿#include <iostream>
using namespace std;
#include <thread>
#include <string>

void printHelloWorld()
{
	cout << "打印 Hello World 线程开始" << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << "Hello World" << endl;
		this_thread::sleep_for(chrono::milliseconds(500));
	}	
	cout << "打印 Hello World 线程结束" << endl;
}

void printAString(string str)
{
	cout << "打印字符串线程开始" << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << str << endl;
		this_thread::sleep_for(chrono::milliseconds(500));
	}
	cout << "打印字符串线程结束" << endl;
}

/**
 * @brief 测试 join
 * @note join 会阻塞主线程，主线程死等子线程执行完毕
 */
void test1(void)
{
	thread theThread1(printHelloWorld);
	theThread1.join();//在此死等，不是我想要的
	thread theThread2(printAString, "1234567");
	theThread2.join();
}

/**
 * @brief 测试 detach
 * @note detach 不会阻塞主线程，要注意，必须确保子线程执行完毕后，主线程才执行完毕 
 */
void test2(void)
{
	thread theThread1(printHelloWorld);
	theThread1.detach();
	thread theThread2(printAString, "1234567");
	theThread2.detach();

	cout << "主线程休眠" << endl;
	this_thread::sleep_for(chrono::milliseconds(10000));
	cout << "主线程休眠结束" << endl;
}


int main(void)
{
	//创建线程测试
	cout << "创建线程测试" << endl;

	////创建线程
	//thread theThread1(printHelloWorld);
	///*join只能用一次，这个joinable就是判断用过没有？
	//*/
	//bool isJoin = theThread1.joinable();
	//if (isJoin)
	//{
	//	//等待线程执行完毕
	//	theThread1.join();
	//}


	//thread theThread2(printAString, "1234567abcde");
	////分离线程
	//theThread2.detach();

	///*join是需要主线程回收子线程资源，detach是主线程与子线程分离，子线程退出后的资源由其他进程回收、
	//*/


	test2();

	
	return 0;
}